package cn.ad.server.common.utils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author dongbin.yu
 * @from 2016-05-30
 * @since V1.0
 */
public class IPUtils {

	private static Logger logger = LoggerFactory.getLogger(IPUtils.class);
	
	/**
	 * 主机名称
	 */
	private static String hotstName = null;

	public static long convertIPToLong(String ip) {
		InetAddress IPAddr = null;
		try {
			IPAddr = InetAddress.getByName(ip);
		} catch (UnknownHostException e) {
			logger.error("ip could not parse, please check the ip is spell correct");
		}

		if (IPAddr == null) {
			return 0L;
		} else {
			byte[] bytes = IPAddr.getAddress();
			if (bytes.length < 4) {
				return 0L;
			} else {
				long l0 = (long) (bytes[0] & 255);
				long l1 = (long) (bytes[1] & 255);
				long l2 = (long) (bytes[2] & 255);
				long l3 = (long) (bytes[3] & 255);
				return l0 << 24 | l1 << 16 | l2 << 8 | l3;
			}
		}
	}

	public static String convertLongToIP(long ipInJava) throws UnknownHostException {
		byte[] bytes = new byte[] { (byte) ((int) ((ipInJava >> 24) % 256L)), (byte) ((int) ((ipInJava >> 16) % 256L)),
				(byte) ((int) ((ipInJava >> 8) % 256L)), (byte) ((int) (ipInJava % 256L)) };
		InetAddress IPAddr = InetAddress.getByAddress(bytes);
		return IPAddr.getHostAddress();
	}

	public static String parseIp(HttpServletRequest request) {

		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	public static String getHostIP() {
		try {
			InetAddress addr = InetAddress.getLocalHost();
			return addr.getHostAddress().toString();
		} catch (Exception e) {
			return "";
		}
	}

	public static List<String> getAllHostIPs() {
		List<String> ips = new ArrayList<String>();
		try {
			for (final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces
					.hasMoreElements();) {
				final NetworkInterface cur = interfaces.nextElement();

				if (cur.isLoopback()) {
					continue;
				}

				// System.out.println("interface " + cur.getName());

				for (final InterfaceAddress addr : cur.getInterfaceAddresses()) {
					final InetAddress inetAddr = addr.getAddress();

					if (!(inetAddr instanceof Inet4Address)) {
						continue;
					}

					// System.out.println(" address: " +
					// inetAddr.getHostAddress() + "/" +
					// addr.getNetworkPrefixLength());
					ips.add(inetAddr.getHostAddress());
				}
			}
		} catch (Exception e) {

		}
		return ips;
	}
	
	/**
	 * 获取主机名
	 * @return
	 */
	public static String getHostName() {
		if(hotstName == null){
			try {
				InetAddress addr = InetAddress.getLocalHost();
				hotstName = addr.getHostName();
			} catch (Exception e) {
				logger.error("获取主机名时出现异常," + e.getMessage(), e);
				return "";
			}
		}
		return hotstName;
	}

	public static long getHostIPToLong() {
		String hostIp = getHostIP();
		if (StringUtils.isEmpty(hostIp))
			return 0;
		return convertIPToLong(hostIp);
	}

	public static String getHostID() {
		return getHostName();
	}

	// public static void main(String[] args) {
	// System.out.println(getAllHostIPs().toString().hashCode());
	// }

}
